﻿using System.Collections;
using System.Collections.Generic;
using GameProtocol;
using GameProtocol.DTO;
using UnityEngine;

public class GlobalInit : MonoBehaviour
{
    private UISceneInitView m_UISceneInitView;
    /// <summary>
    /// 套接字句柄
    /// </summary>
    [HideInInspector]
    public int SocketHandle;
    void Start()
    {
        PlayerPrefs.DeleteAll();
        Instance = this;
        Initialize();
       
    }

    public static GlobalInit Instance { get; private set; }
    private void Initialize()
    {
        #region  静态数据读取例子
        DataTableManager.GetInstance();
        JSONObject str = DataTableManager.PlotTable.FindByAllCondition("Keyid=11");
        Debug.Log(str);
        #endregion
        
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
        //AudioBackGroundManager.CreateInstance();
        UIViewManager.CreateInstance();
        UIViewManager.Instance.LoadSceneUIFromAssetBundle(UIViewManager.SceneUIType.Init);
        //LPSManager.CreateInstance();
        //LogSystem.CurrentLogMode = m_LogMode;
        //NetDispatcher.Instance.AddEventListener(OP_SYS_ERROR.CODE, OnServerError);
        //NetWorkHttp.Instance.OnTokenError = OnTokenError;
        //LPSManager.Instance.StartGPS(null);
        //NetWorkSocket.CreateInstance();
        ConnectServer("127.0.0.1", 8699);
    }
    public void ConnectServer(string ip, int port)
    {
        if (NetWorkSocket.Instance.Connected(SocketHandle))
        {
            OnConnectedCallBack(true);
            return;
        }
        UIViewManager.Instance.ShowWait();
        SocketHandle = NetWorkSocket.Instance.BeginConnect(ip, port, OnConnectedCallBack);
    }
    private void OnConnectedCallBack(bool isSuccess)
    {
        UIViewManager.Instance.CloseWait();
        if (isSuccess)
        {
            Debug.Log("网络连接成功");
            UIViewManager.Instance.OpenWindow(UIWindowType.Login);
        }
        else
        {
            Debug.LogWarning("网络连接失败,请重新尝试");
            UIViewManager.Instance.ShowMessage("错误提示", "网络连接失败,请重新尝试", MessageViewType.OkAndCancel);
        }
    }


    // Update is called once per frame
    void Update()
    {

    }
    #region Variable
    /// <summary>
    /// 服务器时间差(客户端比服务器快多长时间 ms) 
    /// </summary>
    [HideInInspector]
    public long TimeDistance;

    /// <summary>
    /// 当前服务器时间
    /// </summary>
    public long CurrentServerTime
    {
        get
        {
            return TimeUtil.GetTimestampMS() - TimeDistance;
        }
    }
    /// <summary>
    /// 当前版本信息
    /// </summary>
    public Version CurrentVersion;
    #endregion
}
